<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Request;
use think\Cache;
use EasyWeChat\OpenPlatform\Server\Handlers\UpdateAuthorized;

/**
 * @Chatgpt接口
 */
class Chatgpt extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['fileMove'];
    //protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * @文本生成
     * @param unknown $content
     */
    public function index($content = null, $max_tokens = 500)
    {        
        if (!$content) {
            $this->error('问题内空不能为空！');
        }
        
        $redisKey = 'messages' . $this->auth->id;
        $messages = Cache::store('redis')->get($redisKey);
        if ($messages) {
            if (count($messages) > 20){  //只保存最新100条
                array_shift($messages);   //删除第一条
                array_shift($messages);   
            }
        }
          
        $createTime = time();
        $data['uid'] = $this->auth->id;
        $data['ask'] = $content;
        $data['createtime'] = $createTime;
        $chatId = db('chatgpt')->insertGetId($data);
        
        $messages[] = ['role' => 'user', 'content' => $content];
        //$messages[] = ['role' => 'user', 'content' => "在{$max_tokens}个字以内回答,".$content];
        Cache::store('redis')->set($redisKey, $messages);
        $Authorization = Request::instance()->header('Authorization');
        $url = 'https://api.gpt.ge/v1/chat/completions';
        $headers = ['Content-Type:application/json', 'Authorization:Bearer '.$Authorization];
        $params['model'] = 'gpt-3.5-turbo';
        $params['messages'] = $messages;
        $params['max_tokens'] = intval($max_tokens);
       
        $res = http_request($url, $headers, json_encode($params));
        $resArr = json_decode($res, 1);
        if (isset($resArr['error'])) {
            $this->error($resArr['error']['message']);
        }
        $answer = $resArr['choices'][0]['message']['content'];
        $messages[] = ['role' => 'system', 'content' => $answer];
        Cache::store('redis')->set($redisKey, $messages);
        
        $update['answer'] = $answer;
        $update['updatetime'] = time();
        db('chatgpt')->where('id', $chatId)->update($update);
        
        $this->success('Chatgpt返回成功', $resArr);
    }
    
    
    public function indexs($content = null)
    {
        if (!$content) {
            $this->error('问题内容不能为空！');
        }
        $Authorization = Request::instance()->header('Authorization');
        $url = 'https://api.gpt.ge/v1/chat/completions';
        $headers = ['Content-Type:application/json', 'Authorization:Bearer '.$Authorization];
        $params['model'] = 'gpt-3.5-turbo';
        $params['messages'][] = ['role' => 'user', 'content' => $content];
        
        $res = http_request($url, $headers, json_encode($params));
        $resArr = json_decode($res, 1);
        
        $this->success('Chatgpt返回成功', $resArr);
    }
    
    
    /**
     * @AI生成图片
     */
    public function image($prompt = null)
    {
        if (!$prompt) {
            $this->error('图片描述内容不能为空！');
        }
        $Authorization = Request::instance()->header('Authorization');
        $url = 'https://api.gpt.ge/v1/chat/completions';
        $headers = ['Content-Type:application/json', 'Authorization:Bearer '.$Authorization];
        $params['model'] = 'dall-e-3';
        $params['prompt'] = $prompt;
        $params['n'] = 1;
        $params['quality'] = 'hd';
        $params['responseFormat'] = null;
        $params['style'] = null;
        $params['user'] = null;
        $params['size'] = "1024x1024";
        
        $res = http_request($url, $headers, json_encode($params));
        $resArr = json_decode($res, 1);
        
        $this->success('Chatgpt返回成功', $resArr);
    }
    
    
    /**
     * @文本转语音
     */
    public function textToVoice1($input = null) {
        if (!$input) {
            $this->error('文本内容不能为空');
        }
        
        $Authorization = Request::instance()->header('Authorization');
        $url = 'https://api.gpt.ge/v1/audio/speech';
        $headers = ['Content-Type:application/json', 'Authorization:Bearer '.$Authorization];
        $params['model'] = 'tts-1';
        $params['input'] = $input;
        $params['voice'] = 'alloy';
        
        $res = http_request($url, $headers, json_encode($params));
        $fileName = date('YmdHis', time()) . '_' . $this->auth->id . '.mp3';
        file_put_contents($fileName .'.mp3', $res);
        /* $dir = ROOT_PATH.'public'.DS;
        $ret = rename($dir."\\$fileName", $dir."\\uploads\\t2v\$fileName");
        if ($ret) {
            ;
        } else {
            
        } */
        
        $this->success('Chatgpt返回成功', 'http://192.168.1.133/' . $fileName);
    }
    
    
    /**
     * @文本转语音
     */
    public function textToVoice($input = null) {
        if (!$input) {
            $this->error('文本内容不能为空');
        }
        
        //$this->success('Chatgpt返回成功', 'http://192.168.1.133:82/uploads/t2v/20240416084045_1.mp3');        
        $Authorization = Request::instance()->header('Authorization');
        $url = 'https://api.gpt.ge/v1/audio/speech';
        $headers = ['Content-Type:application/json', 'Authorization:Bearer '.$Authorization];
        $params['model'] = 'tts-1';
        $params['input'] = $input;
        $params['voice'] = 'nova';  //女声
        //$params['voice'] = 'alloy';
        //$params['voice'] = 'echo';
        //$params['voice'] = 'fable';
        //$params['voice'] = 'onyx';        
        //$params['voice'] = 'shimmer';  //女声
   
        $res = http_request($url, $headers, json_encode($params));
        $fileName = date('YmdHis', time()) . '_' . $this->auth->id . '.mp3';
        $path = ROOT_PATH.'public' .DS. 'uploads' .DS. 't2v' .DS. $fileName;
        $ret = file_put_contents($path, $res);
        if ($ret) {
            $answerAudio = '/uploads/t2v/'.$fileName;
            $id = db('chatgpt')->order('id', 'DESC')->value('id');
            db('chatgpt')->where('id', $id)->setField('answer_audio', $answerAudio);
            $this->success('Chatgpt返回成功', $answerAudio);
        } else {
            $this->errot('服务器繁忙，请稍后再试！');
        }
    }
    
    
    /**
     * @语音转文本
     */
    public function voiceToText($file = null) {
        // 确保这个脚本运行在文件开始标记后
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            // 检查是否有文件被上传
            if (isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK) {
                // 设置上传目录
                $uploadDir = 'uploads/v2t/';
                /* if (!is_dir($uploadDir)) {
                 mkdir($uploadDir, 0755, true);
                 } */
                // 设置上传文件的路径
                $uploadFile = $uploadDir . date('Ymd-His', time()) . '_' . $this->auth->id . '.mp3';
                // 移动上传的文件到指定目录
                if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
                    echo "文件上传失败。";
                }
                
                //保存问的音频
                $id = db('chatgpt')->order('id', 'DESC')->value('id');
                db('chatgpt')->where('id', $id)->setField('ask_audio', '/'.$uploadFile);
                
                $Authorization = Request::instance()->header('Authorization');
//                 $url = 'https://api.gpt.ge/v1/audio/transcriptions';
                $url = 'https://api.gpt.ge/v1/audio/transcriptions';
                $headers = ['Authorization:Bearer '.$Authorization];
                $params['model'] = 'whisper-1';
                $params['file'] = new \CURLFile($uploadFile, 'audio/mp3', $this->auth->id.'speech.mp3');
                $res = http_request($url, $headers, $params);
                $resArr = json_decode($res, 1);
                
                if (isset($resArr['error'])) {
                    $this->error('Chatgpt返回失败', $resArr['error']['message']);
                }
                
                $this->success('Chatgpt返回成功', $resArr);
            } else {
                // 没有文件被上传
                echo "没有文件上传。";
            }
        } else {
            // 请求方法不是POST
            echo "请使用POST方法上传文件。";
        }
    }
    
    
    public function fileMove(){
        $dir = ROOT_PATH.'public'.DS;
        $fileName = 'speech.mp3';
        $ret = rename($dir."\\$fileName", $dir."\\uploads\\t2v\$fileName");
    }
    

    /**
     * @语音转文本
     */
    public function voiceToText1($file = null) {
        $file = $this->request->file('file');
        if (!$file) {
            $this->error('语音文件不能为空');
        }
        
        $info = $file->move(ROOT_PATH.'public'.DS.'uploads'.DS.'v2t');
        $filename = $info->getSaveName();
        $filePath = "D:\\www\dhuman\\public\\uploads\\v2t\\" . $filename;
        
        $Authorization = Request::instance()->header('Authorization');
        $url = 'https://api.gpt.ge/v1/audio/transcriptions';
        $headers = ['Authorization:Bearer '.$Authorization];
        $params['model'] = 'whisper-1';        
        $params['file'] = new \CURLFile($filePath, 'audio/mp3', 'speech.mp3');        
        $res = http_request($url, $headers, $params);
        $resArr = json_decode($res, 1);
        
        if (isset($resArr['error'])) {
            $this->error('Chatgpt返回失败', $resArr['error']['message']);
        }
        
        $this->success('Chatgpt返回成功', $resArr);
    }
    
}
